<template>
  <div class="bigbox">
    <!-- 页面头部盒子 -->
    <div class="topbox" :style="{ height: isheight + 'px' }">
      <el-form
        :model="form"
        ref="form"
        label-position="left"
        label-width="70px"
      >
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="用电企业">
              <FilterSelect2
                v-model="form.orgNo"
                @updateModelValue="changeqiye"
                :optionlist="qiyelist"
                :valuekey="{ name: 'bizOrgName', value: 'bizOrgNo' }"
              ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="8" style="display: flex; margin-top: 4px">
            <el-radio-group
              v-model="radio3"
              size="small"
              style="margin-right: 20px"
            >
              <el-radio-button label="日"></el-radio-button>
              <el-radio-button label="月"></el-radio-button>
              <el-radio-button label="年"></el-radio-button>
            </el-radio-group>
            <template v-if="radio3 == '日'">
              <el-date-picker
                v-model="value1"
                style="flex: 1"
                size="small"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetimerange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </template>
            <template v-else-if="radio3 == '月'">
              <el-date-picker
                v-model="value2"
                value-format="yyyy-MM"
                style="flex: 1"
                type="month"
                size="small"
                placeholder="选择月"
              >
              </el-date-picker>
            </template>
            <template v-else>
              <el-date-picker
                v-model="value3"
                value-format="yyyy"
                style="flex: 1"
                type="year"
                size="small"
                placeholder="选择年"
              >
              </el-date-picker>
            </template>
          </el-col>
          <el-col :span="5">
            <el-form-item label="配电室">
              <FilterSelect2
                v-model="form.switchroomId"
                @updateModelValue="changepei"
                :optionlist="peidianlist"
                :valuekey="{ name: 'name', value: 'id' }"
              ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="设备">
              <div >
                <el-select
                  v-model="form.bayId"
                  multiple
                  size="small"
                  collapse-tags
                  class="all"
                  @change="changeshebei"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in shebeilist"
                    :key="item.value"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
                <!-- <el-button
                  @click="toggleAllSelect"
                  size="small"
                  type="primary"
                  >{{ isAllSelected ? '全不选' : '全选' }}</el-button> -->
                  <el-dropdown @command="toggleAllSelect">
                    <span class="el-dropdown-link">
                      <el-button type="primary" size="small" icon="el-icon-info" ></el-button>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item :command="true">全选</el-dropdown-item>
                      <el-dropdown-item :command="false">全不选</el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown>
              </div>
            </el-form-item>
          </el-col>
          <el-col
            :span="24"
            v-show="!isshow"
            style="text-align: right; margin-top: 4px"
          >
            <el-button @click="chingzhi" size="small">重 置</el-button>
            <el-button @click="gettablelist()" size="small" type="primary">
              查 询
            </el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 页面主体 -->
    <div class="bodybox">
      <!-- :style="{height: `calc(${num}% - ${number}px)`}" -->
      <div class="paiming">
        <div class="no noone">
          <div><img src="../../../assets/statis/image.png" alt="" /></div>
          <div class="nameadval">
            <div>{{ topThree[0]?.bayName }}</div>
            <div class="no1">
              <span>{{ topThree[0]?.epowerTotal }}</span
              ><span class="kwh">kWh</span>
            </div>
          </div>
        </div>
        <div class="no notwo">
          <div><img src="../../../assets/statis/image copy.png" alt="" /></div>
          <div class="nameadval">
            <div>{{ topThree[1]?.bayName }}</div>
            <div class="no2">
              <span>{{ topThree[1]?.epowerTotal }}</span
              ><span class="kwh">kWh</span>
            </div>
          </div>
        </div>
        <div class="no nothree">
          <div>
            <img src="../../../assets/statis/image copy 2.png" alt="" />
          </div>
          <div class="nameadval">
            <div>{{ topThree[2]?.bayName }}</div>
            <div class="no3">
              <span>{{ topThree[2]?.epowerTotal }}</span
              ><span class="kwh">kWh</span>
            </div>
          </div>
        </div>
      </div>
      <!--表格/图表区域 -->
      <div class="tabech">
        <div class="echarts">
          <!-- 内堆图 -->
          <div class="echartone">
            <div style="text-align: center">
              {{ objname?.bayName }} 电量结构
            </div>
            <!-- 电量结构图表 -->
            <div class="dianlang" ref="dianlang"></div>
          </div>
          <!-- 饼图 -->
          <div class="echartone echarttwo">
            <div style="text-align: center">
              {{ objname?.bayName }} 尖峰占比
            </div>
            <!-- 峰谷占比图表 -->
            <div class="fenggu" ref="fenggu"></div>
          </div>
        </div>
        <!-- 主体头部 -->
        <div
          style="display: flex; justify-content: space-between; margin: 20px 0"
        >
          <div>重点设备电量</div>
          <div class="titlebox">
            <el-button type="primary" size="small" @click="daochu">
              <i class="el-icon-upload2">导出</i>
            </el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="刷新"
              placement="top"
            >
              <span @click="shuaxin"
                ><i class="el-icon-refresh-right" style="cursor: pointer"></i
              ></span>
            </el-tooltip>
            <el-dropdown trigger="click" @command="command">
              <span class="el-dropdown-link">
                <el-tooltip
                  class="item"
                  effect="dark"
                  content="密度"
                  placement="top"
                >
                  <span
                    ><i class="el-icon-d-caret" style="cursor: pointer"></i
                  ></span>
                </el-tooltip>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="默认">默认</el-dropdown-item>
                <el-dropdown-item command="中等">中等</el-dropdown-item>
                <el-dropdown-item command="紧凑">紧凑</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
        <div class="table">
          <template>
            <el-table
              ref="table"
              v-loading="loading"
              border
              :size="iissize"
              highlight-current-row
              :header-cell-style="{
                'text-align': 'center',
                background: '#f5f5f5'
              }"
              @current-change="handleCurrentChange"
              :data="tableData"
              style="width: 100%"
            >
              <el-table-column
                prop="switchroomName"
                label="配电室"
                align="center"
              >
              </el-table-column>
              <el-table-column prop="bayName" label="设备" width="300">
              </el-table-column>
              <el-table-column prop="epowerJsd" align="right" label="尖(kWh)">
              </el-table-column>
              <el-table-column prop="epowerFsd" label="峰(kWh)" align="right">
              </el-table-column>
              <el-table-column prop="epowerPsd" label="平(kWh)" align="right">
              </el-table-column>
              <el-table-column prop="epowerGsd" align="right" label="谷(kWh)">
              </el-table-column>
              <el-table-column
                prop="epowerTotal"
                label="总电量(kWh)"
                align="right"
              >
              </el-table-column>
              <el-table-column prop="fgPercent" label="尖峰占比" align="right">
              </el-table-column>
              <el-table-column
                prop="degreeCharge"
                align="right"
                label="电度电费(元)"
              >
              </el-table-column>
              <el-table-column
                prop="avgPrice"
                align="right"
                label="平均电价(元/kWh)"
                width="150"
              >
              </el-table-column>
            </el-table>
          </template>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { getuserlistapi } from '@/api/analysis'
import { saveAs } from 'file-saver'
import dayjs from 'dayjs'
import {
  geipeidiansapi,
  getshebeiapi,
  gettablelistapi,
  exporttableapi
} from '@/api/keynote'
import * as echarts from 'echarts'
export default {
  name: 'CallPoliceIndex',
  data() {
    return {
      number: 90,
      num: 100,
      iissize: '',
      radio3: '日',
      value1: [],
      value2: '',
      value3: '',
      bizOrgName: '',
      isshow: false,
      isheight: 120,
      form: { switchroomName: '', bayName: [], bayId: [] },
      qiyelist: [],
      shebeilist: [],
      peidianlist: [],
      tableData: [],
      bingtulist: [],
      junlist: [],
      iissize: 'medium',
      fgPercent: '',
      objname: {},
      loading: false,
      topThree: []
    }
  },

  async mounted() {
    this.gettime()
    const res = await getuserlistapi()
    this.qiyelist = res.data.list
    this.form.orgNo = this.$store.state.statistics.userbizOrgNo
      ? this.$store.state.statistics.userbizOrgNo
      : res.data.list[0].bizOrgNo
    await this.getpeidianxiala(this.form.orgNo)
    this.gettablelist()
    this.getbinecharts()
    this.gethuanxingtu()
  },

  methods: {
    // 获取表格数据
    async gettablelist() {
      if (!this.form.switchroomId)
        return this.$message.warning('配电室不可为空')
      this.loading = true
      const { orgNo, switchroomId, bayName, bayId, switchroomName } = this.form
      const time = this.value1.join('_')
      const periodType =
        this.radio3 == '日' ? 'time' : this.radio3 == '月' ? 'month' : 'year'
      const res = await gettablelistapi({
        orgNo,
        switchroomId,
        switchroomName,
        bayId: bayId.join(','),
        periodType,
        bayName: bayName.join(','),
        dateStr:
          this.radio3 == '日'
            ? time
            : this.radio3 == '月'
            ? this.value2
            : this.value3
      })
      this.tableData = res.data.list
      this.topThree = res.data.list.sort(
        (a, b) => parseFloat(b.epowerTotal) - parseFloat(a.epowerTotal)
      ) // 降序排序.slice(0, 3);
      this.loading = false
      this.$refs.table.setCurrentRow(this.tableData[0])
      this.getbinecharts()
      this.gethuanxingtu()
    },
    // 获取配电室下拉
    async getpeidianxiala(id) {
      const res = await geipeidiansapi({ orgNo: id })
      this.peidianlist = res.data.list
      this.form.switchroomId = res.data.list[0]?.id
      this.form.switchroomName = this.peidianlist.filter(
        (ele) => ele.id == this.form.switchroomId
      )[0]?.name
      if (this.form.switchroomId) {
        await this.getshebeixiala(res.data.list[0]?.id)
      } else {
        this.shebeilist = []
        this.form.bayId = []
        this.form.bayName = []
      }
    },
    // 获取设备下拉
    async getshebeixiala(id) {
      const res = await getshebeiapi({ orgNo: this.form.orgNo, pathId: id })
      this.shebeilist = res.data.list || [] // 真实设备列表（无“全选”选项）

      // 初始化全选状态：选中所有设备，标记为全选
      this.form.bayId = this.shebeilist.map((ele) => ele.id)
      this.form.bayName = this.shebeilist.map((ele) => ele.name)
    },
    // 企业下拉框选择
    changeqiye(val) {
      this.getpeidianxiala(val)
      this.$forceUpdate()
      this.$store.commit('setuserobject', val)
    },
    // 配电室下拉
    changepei(val) {
      this.$forceUpdate()
      this.getshebeixiala(val)
      this.form.switchroomName = this.peidianlist.filter(
        (ele) => ele.id == val
      )[0]?.name
    },
    // 设备下拉
    changeshebei(selectedIds) {
      this.form.bayName = selectedIds
        .map((id) => {
          const matchItem = this.shebeilist.find((item) => item.id === id)
          return matchItem ? matchItem.name : ''
        })
        .filter((name) => name)
    },
    toggleAllSelect(val) {
      if (!val) {
        this.form.bayId = []
        this.form.bayName = []
      } else {
        this.form.bayId = this.shebeilist.map((ele) => ele.id)
        this.form.bayName = this.shebeilist.map((ele) => ele.name)
      }
    },
    // 导出表格
    async daochu() {
      const { orgNo, switchroomId, bayName, bayId, switchroomName } = this.form
      const time = this.value1.join('_')
      const periodType =
        this.radio3 == '日' ? 'time' : this.radio3 == '月' ? 'month' : 'year'
      const orgName = this.qiyelist.filter(
        (ele) => ele.bizOrgNo == this.form.orgNo
      )[0].bizOrgName
      const res = await exporttableapi({
        orgNo,
        switchroomId,
        switchroomName,
        bayId: bayId.join(','),
        periodType,
        bayName: bayName.join(','),
        dateStr:
          this.radio3 == '日'
            ? time
            : this.radio3 == '月'
            ? this.value2
            : this.value3,
        orgName: orgName,
        isParams: true
      })
      const blobContent = new Blob([res])
      let url = window.URL.createObjectURL(blobContent)
      saveAs(url, '设备电量分析.xls')
    },
    // 刷新列表
    shuaxin() {
      this.gettablelist()
      this.$message.success('数据刷新成功')
    },
    // 搜索栏折叠
    zedie() {
      this.isshow = !this.isshow
      if (this.isshow) {
        this.isheight = 190
        this.number = 200
      } else {
        this.isheight = 130
        this.number = 140
      }
    },
    // 调节表格密度
    command(val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },
    // 表格点击事件
    handleCurrentChange(val) {
      this.objname = val
      this.bingtulist = [
        { name: '尖', value: val ? val.epowerJsd : '0' },
        { name: '峰', value: val ? val.epowerFsd : '0' },
        { name: '平', value: val ? val.epowerPsd : '0' },
        { name: '谷', value: val ? val.epowerGsd : '0' }
      ]
      this.junlist = [{ name: '平均电价', value: val ? val.avgPrice : '0' }]
      this.fgPercent = val ? val.fgPercent : ''
      this.getbinecharts()
      this.gethuanxingtu()
    },
    // 获取饼图图表
    getbinecharts() {
      var chartDom = this.$refs.dianlang
      var myChart = echarts.init(chartDom)
      var option
      let richColor = {}
      let pieColors = ['#ff6666', '#5996ff', '#18f2ce', '#ffbe4c']
      pieColors.forEach((item, idx) => {
        richColor[`color${idx}`] = {
          fontSize: 14,
          color: item
        }
      })
      option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          data: ['尖', '峰', '平', '谷'],
          top: 'bottom'
        },
        color: pieColors,
        series: [
          {
            name: '平均电价',
            type: 'pie',
            selectedMode: 'single',
            radius: [0, '30%'],
            label: {
              position: 'center',
              formatter: '{c}\n{a}  ',
              fontSize: 14
            },
            labelLine: {
              show: false
            },
            data: this.junlist,
            color: ['green']
          },
          {
            name: '',
            type: 'pie',
            radius: ['45%', '60%'],
            labelLine: {
              length: 30
            },
            label: {
              // formatter: '{b} {d}% \n{c}(kwh) ',
              formatter: (params) => {
                return `{color${params.dataIndex}|${params.name}${params.percent}%\n${params.value}(kWh)}`
              },
              rich: richColor
            },
            // data: [
            //   { value: 1048, name: '尖' },
            //   { value: 335, name: '峰' },
            //   { value: 310, name: '平' },
            //   { value: 251, name: '谷' }
            // ]
            data: this.bingtulist
          }
        ]
      }

      option && myChart.setOption(option)
      window.addEventListener('resize', () => {
        //图表响应处理
        myChart.resize()
      })
    },
    // 获取环形图图表
    gethuanxingtu() {
      var chartDom = this.$refs.fenggu
      var myChart = echarts.init(chartDom)
      // const data=75
      var option

      option = {
        title: {
          text: this.fgPercent + '%', //主标题文本
          left: '50%',
          top: '45%',
          textStyle: {
            fontWeight: 'normal',
            fontSize: 18,
            color: '#FF974C',
            align: 'center',
            left: 10
          },
          subtextStyle: {
            fontSize: 13,
            color: '#6c7a89'
          }
        },
        tooltip: {
          trigger: 'item',
          formatter: '{d}%',
          show: true
        },
        series: [
          {
            name: 'Access From',
            type: 'pie',

            // button:'50%',
            radius: ['50%', '65%'],
            center: ['53%', '50%'],
            avoidLabelOverlap: false,
            hoverAnimation: false,
            label: {
              normal: {
                show: false,
                position: 'center'
              },
              emphasis: {
                show: false
              }
            },
            labelLine: {
              normal: {
                show: false
              }
            },
            data: [
              {
                value: this.fgPercent,
                name: '峰谷占比',
                selected: false,
                itemStyle: {
                  color: '#FF974C'
                }
              },
              {
                value: 100 - this.fgPercent,
                name: '',
                itemStyle: {
                  color: '#E9EEF4'
                },
                label: {
                  normal: {
                    show: false
                  }
                }
              }
            ]
          }
        ]
      }

      option && myChart.setOption(option)
      window.addEventListener('resize', () => {
        //图表响应处理
        myChart.resize()
      })
    },
    // 获取当前时间戳
    gettime() {
      this.value1 = [
        dayjs().format('YYYY-MM-DD 00:00:00'),
        dayjs().format('YYYY-MM-DD HH:mm:ss')
      ]
      this.value2 = dayjs().format('YYYY-MM')
      this.value3 = dayjs().format('YYYY')
    },
    // 重置
    async chingzhi() {
      this.radio3 = '日'
      this.form.bayId = []
      this.gettime()
      const res = await getuserlistapi()
      this.qiyelist = res.data.list
      this.form.orgNo = res.data.list[0].bizOrgNo
      await this.getpeidianxiala(res.data.list[0].bizOrgNo)
      this.gettablelist()
      this.getbinecharts()
      this.gethuanxingtu()
    }
  }
}
</script>

<style lang="scss" scoped>
.dengji {
  padding-left: 10px;
}
.bigbox {
  height: 100%;
  .topbox {
    background-color: #fff;
    padding: 20px;
    // padding: 20px;
    box-sizing: border-box;
    width: 100% !important;
    .all {
      margin-right: 5px;
      width: calc(100% - 49px);
    }
  }
  .bodybox {
    background-color: #fff;
    padding: 20px;
    .paiming {
      height: 130px;
      margin-bottom: 20px;
      display: flex;
      justify-content: space-between;
      .no {
        width: 30%;
        border-radius: 10px;
        display: flex;
        .nameadval {
          display: flex;
          flex-direction: column;
          justify-content: center;
          margin-left: 10px;
          font-size: 20px;
          color: #000;
          .no1 {
            color: #d0a05e;
            margin-top: 15px;
          }
          .no2 {
            color: #bbc7cf;
            margin-top: 15px;
          }
          .no3 {
            color: #6d6988;
            margin-top: 15px;
          }
          .kwh {
            font-size: 14px;
          }
        }
      }
      .noone {
        background-color: #faf6ef;
        border: 2px solid #ecd9bf;
      }
      .notwo {
        background-color: #f8fafa;
        border: 2px solid #bbc7cf;
      }
      .nothree {
        background-color: #f1f0f3;
        border: 2px solid #6d6988;
      }
    }
    .titlebox {
      text-align: right;
      .daochu {
        width: 60px;
        height: 30px;
        background-color: #1890ff;
        color: #fff;
        border: none;
        border-radius: 3px;
      }
      .item {
        margin-left: 10px;
      }
    }
    .tabech {
      margin-top: 15px;
      height: 95%;
      .echarts {
        display: flex;
        height: 300px;
        .echartone {
          width: 50%;
          height: 100%;
          .dianlang {
            height: 90%;
          }
          .fenggu {
            height: 90%;
          }
        }
        .echarttwo {
          width: 50%;
          margin-top: 20px;
        }
      }
    }
  }
}
.bodybox {
  background-color: #fff;
  margin-top: 10px;
  padding: 20px 20px 20px 30px;
}
</style>
